<template>
    <div class="page-container">
        <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="文件夹权限列表" name="config" v-if="showConfig">
                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button
                            type="primary"
                            plain
                            icon="el-icon-plus"
                            size="mini"
                            @click="handleAddDir"
                        >AddFileDir
                        </el-button>
                    </el-col>
                </el-row>
                <el-table
                    :data="filesConfigList"
                    style="width: 100%">
                    <el-table-column
                        prop="menuName"
                        label="文件夹名称"
                        width="180">
                    </el-table-column>
                    <el-table-column
                        prop="perms"
                        label="权限">
                    </el-table-column>
                    <el-table-column label="Operate" align="center" class-name="small-padding fixed-width">
                        <template slot-scope="scope">
                            <el-button
                                size="mini"
                                type="text"
                                icon="el-icon-delete"
                                @click="handleDelete(scope.row)"
                                v-hasPermi="['business:goodCatch:remove']"
                            >Delete
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>

            <el-tab-pane v-for="(item,index) in treeData" :label="item.label" :name="'pane'+index">
                <el-form  size="small" :inline="true" >
                    <el-form-item label="Input" prop="roleName">
                        <el-input
                            v-model="searchValue"
                            placeholder="Input"
                            clearable
                            style="width: 240px"
                            @keyup.enter.native="handleQuery"
                        />
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery(item.label)">Search</el-button>
                        <el-button icon="el-icon-refresh" size="mini" @click="handleReset">Reset</el-button>
                    </el-form-item>
                </el-form>

                <el-table  v-if="item.children.length > 0"
                    :data="item.children"
                    style="width: 100%;margin-bottom: 20px;"
                    row-key="filePath"
                    border
                    default-expand-all
                    :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
                    <el-table-column
                        prop="label"
                        label="文件夹"
                        sortable
                        width="auto">
                    </el-table-column>
                    <el-table-column
                        prop="Operate"
                        label="操作">
                        <template slot-scope="scope">
                            <el-button
                                v-if="scope.row.isFile"
                                type="text"
                                size="mini"
                                @click="() => downloadFile(scope.row)">
                                下载
                            </el-button>
                            <el-button
                                v-if="scope.row.isFile && scope.row.label.endsWith('.pdf')"
                                type="text"
                                size="mini"
                                @click="() => viewPdf(scope.row)"
                               > 预览
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>
        </el-tabs>
        <!-- 添加或修改goodCatch对话框 -->
        <el-dialog title="增加文件夹" :visible.sync="open" width="50%" :append-to-body="true"
                   :close-on-click-modal="false">
            <el-form ref="form" :model="newFileForm" label-width="auto">
                <el-form-item label="文件夹名称" prop="menuName">
                    <el-input v-model="newFileForm.menuName" placeholder="Input FileDirName"/>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">Submit</el-button>
                <el-button @click="cancel">Cancel</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<style>
.page-container {
    margin-left: 20px; /* 调整这个值以实现您想要的右移效果 */
}
</style>
<script>
import {addFilesConfig, deleteFilesConfig, getFilesConfig, listPath} from "@/api/business/dcc";
import {download, downloadBlob} from "@/utils/request";

export default {
    data() {
        return {
            showConfig:false,
            newFileForm: {
                menuName: '',
                perms: ''
            },
            open: false,
            filesConfigList: [],
            activeName: '',
            originTreeData:[],
            treeData: [],
            subTreeData: [],
            pdfList: [], // 存储PDF文件信息的数组
            pdfUrl:'',
            searchValue:''
        };
    },
    components:{},
    methods: {
        handleFilter(item,searchValue){
            let newChildren = []
            // 递归遍历本文件夹下的子文件夹
            let children =  item.children
            if (children.length >0){
                for (let i = 0; i < children.length; i++){
                    const oldChildren = children[i]
                    // 如果有符合的加入
                    let newChildrenItem = this.handleFilter(oldChildren, searchValue)
                    if (newChildrenItem !== null){
                        newChildren.push(newChildrenItem)
                    }
                }
            }
            // 处理当前文件夹下的文件
            let label = item.label
            // 如果搜索的值中包含字母转化成大写
            let searchValueCopy = '';
            for(let i = 0 ; i< searchValue.length ;i++){
                if (/^[a-zA-Z]*$/.test(searchValue.charAt(i))){
                    searchValueCopy += searchValue.charAt(i).toUpperCase()
                }else{
                    searchValueCopy += searchValue.charAt(i)
                }
            }
            // 找到最后的文件名
            let fileNameCopy = label
            let newFileName = ''
            // 如果文件名的值中包含字母转化成大写
            for(let i = 0 ; i< fileNameCopy.length ;i++){
                if (/^[a-zA-Z]*$/.test(fileNameCopy.charAt(i))){
                    newFileName += fileNameCopy.charAt(i).toUpperCase()
                }else{
                    newFileName += fileNameCopy.charAt(i)
                }
            }
            console.log("searchCopy:",searchValueCopy,"fileNameCopy: ",fileNameCopy,fileNameCopy.indexOf(searchValue.toUpperCase()))
            item.children = newChildren
            // 如果当前字段不包含搜索  但是 子文件包含 或者当前字段包含搜索，且没有子文件，则返回当前节点
            if (newFileName.indexOf(searchValueCopy.toUpperCase()) < 0 && newChildren.length > 0 ||
                newFileName.indexOf(searchValueCopy.toUpperCase()) > -1 && newChildren.length ===0  ){
                return item
            }else{
                return null
            }
        },
        handleQuery(label){
            let data = JSON.parse(JSON.stringify(this.originTreeData))
            console.log(data)
            let newData = []
            for(let i = 0; i < data.length ;i++){
                // 判断当前的tab
               if (data[i].label === label){
                   const oldItem = data[i]
                   const newItem =  this.handleFilter(oldItem,this.searchValue)
                   if (null !== newItem){
                       newData.push(newItem)
                   }else{
                       oldItem.children = []
                       newData.push(oldItem)
                   }
               }else{
                   newData.push(data[i])
               }

            }
            if (newData.length < 1){
                this.$message.warning("No file contain")
                this.treeData = JSON.parse(JSON.stringify(this.originTreeData))
            }else{
                this.treeData = JSON.parse(JSON.stringify(newData))
            }
        },
        handleReset(){
            this.searchValue = ''
            this.treeData = JSON.parse(JSON.stringify(this.originTreeData))
        },
        handleClick(tab, event) {
            console.log(tab, event);
            this.searchValue = ''
        },
        downloadFile(node) {
            console.log(node)
            download("/common/downloadAny", {'fileName': node.filePath}, node.label)
        },
        viewPdf(node){
            downloadBlob("/common/downloadAny", {'fileName': node.filePath}, node.label).then(res=>{
                const binaryData = [];
                binaryData.push(res);
                //获取blob链接
                this.pdfUrl = window.URL.createObjectURL(new Blob(binaryData, { type: 'application/pdf' }));
                window.open(this.pdfUrl);
                window.URL.revokeObjectURL(this.pdfUrl);
            })
        },
        loadPdfList() {
            listPath("D:\\testFile\\RB文件",this.searchValue).then((res) => {
                const resData = res.data
                console.log(resData)
                // 增加配置面板
               const data =  this.parseData(resData);
                this.treeData = JSON.parse(JSON.stringify(data))
                console.log( this.treeData)
                this.originTreeData = JSON.parse(JSON.stringify(data))
                this.activeName = 'pane0'
            })
        },
        parseData(data, beginId) {
            if (beginId === undefined || beginId < 0) {
                beginId = 0;
            }
            let res = [];
            // 递归处理当前文件夹下的文件夹
            const dirs = data.dir;
            if (dirs && dirs.length > 0) {
                for (const dir of dirs) {
                    let fileName = dir.path.split("\\");
                    let arr =  this.parseData(dir, ++beginId)
                    res.push({
                        isFile: false,
                        id: ++beginId,
                        label: fileName[fileName.length - 1],
                        filePath: dir.path,
                        children: arr,
                        hasChildren: arr > 0
                    })
                }
            }
            // 处理当前文件夹下的文件
            const files = data.files
            if (files && files.length > 0) {
                for (const file of files) {
                    if (!file.endsWith("pdf")){
                        continue
                    }
                    let fileName = file.split("\\");
                    res.push({
                        isFile: true,
                        id: ++beginId,
                        label: fileName[fileName.length - 1],
                        filePath: file,
                        children: []
                    })
                }
            }
            return res;
        },
        listFileConfig() {
            getFilesConfig().then(res => {
                this.filesConfigList = res.data;
            })
        },
        handleAddDir() {
            this.newFileForm = {};
            this.open = true;
        },
        handleDelete(row){
            const id = row.menuId ;
            this.$modal.confirm('Delete FileDir？').then(function () {
                return deleteFilesConfig(id);
            }).then(() => {
                this.listFileConfig();
                this.$modal.msgSuccess("Delete Success");
            }).catch(() => {
            });
        },
        /** 提交按钮 */
        submitForm() {
            if (undefined === this.newFileForm.menuName || null === this.newFileForm.menuName || this.newFileForm.menuName === '') {
                this.$message({
                    message: '请输入文件夹名称',
                    type: 'error'
                });
                return;
            }
            addFilesConfig(this.newFileForm.menuName).then(res => {
                this.open = false;
                this.$modal.msgSuccess("Add Success");
                this.listFileConfig();
            })
        },
        cancel() {
            this.open = false;
        },
    },
    created() {
        // 如果有权限则请求文件夹权限列表
        if (this.$auth.hasPermi("business:dcc:config")) {
            this.listFileConfig();
            this.showConfig = true;
        }
        this.loadPdfList();
    }
};

</script>
